import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router' 


// 定义路由配置
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    name: 'home',
    component: () => import('../views/Home.vue'),
    meta: {
      title: '首页'
    }
  },
  {
    path: '/routes',
    name: 'routes',
    component: () => import('../views/Routes.vue'),
    meta: {
      title: '线路推荐'
    }
  },
  {
    path: '/news',
    name: 'news',
    component: () => import('../views/News.vue'),
    meta: {
      title: '旅游资讯'
    }
  },
  {
    path: '/user',
    name: 'user',
    component: () => import('../views/Profile.vue'),
    meta: {
      title: '个人中心',
      // requiresAuth: true
    }
  },
  {
    path: '/cart',
    name: 'cart',
    component: () => import('../views/Cart.vue'),
    meta: {
      title: '购物车'
    }
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/Login.vue'),
    meta: {
      title: '登录'
    }
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = `${to.meta.title} - 旅游网站`

  // 检查是否需要登录权限
  if (to.meta.requiresAuth) {
    // 这里需要根据实际的用户认证状态来判断
    // 暂时使用 localStorage 检查是否有 token
    const isAuthenticated = localStorage.getItem('token')
    
    if (!isAuthenticated) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router